#pragma once
#include "TcpServer.hpp"
#include <sstream>
#include "ThreadPool.hpp"
class HttpServer
{
private:
    int _port;
    static HttpServer* _instance;
    TcpServer* _tcp = nullptr;
    bool _stop = false;
private:
    HttpServer(int port):_port(port){}
    HttpServer(const HttpServer&) = delete;
    HttpServer& operator=(const HttpServer&) = delete;
public:
    static HttpServer* GetInstance(int port){
        if(nullptr == _instance){
            pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
            pthread_mutex_lock(&lock);
            if(nullptr == _instance){
                _instance = new HttpServer(port);
            }
            pthread_mutex_unlock(&lock);
        }
        return _instance;
    }
 
    void Loop(){
        _tcp = TcpServer::GetInstance(_port);
        LOG(INFO, "Server Start");
        while(!_stop){
            int client_sock = -1;
            if(_tcp->Accept(&client_sock) == false){
                LOG(WARNING, "Accept error!");
                continue;
            }
            //cout << "client_sock: " << client_sock << endl;
            LOG(INFO, "Get A Link!");
            ThreadPool::GetInstance()->Push(Task(client_sock));
        }
        return;
    }

};
HttpServer* HttpServer::_instance = nullptr;